package com.usky.pss.refundticket.work;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by Jeremy on 2016/11/11.
 */
public class WorkerMaster {


    //创建一个线程安全的任务队列，存放所有任务
    private ConcurrentLinkedQueue<TicketStatusTask> workQueue = new ConcurrentLinkedQueue<>();
    //创建一个worker的容器，用于多线程并发
    private List<Thread> workerList = new ArrayList<>();
    //创建一个线程安全的任务处理结果容器
    private ConcurrentHashMap<String,TicketStatusTask> workResult = new ConcurrentHashMap<>();

    public WorkerMaster(TicketStatusWorker worker, int workerCount ){
        worker.setWorkQueue(this.workQueue);
        worker.setWorkResult(this.workResult);
        for (int i = 0;i < workerCount;i++){
            workerList.add(new Thread(worker));
        }
    }

    //提交任务
    public void submit(TicketStatusTask task){
        this.workQueue.add(task);
    }

    //启动所有worker执行任务
    public void execute(){
        for (Thread thread : this.workerList){
            thread.start();
        }
    }
    public void execute2(TicketStatusWorker worker){
        worker.run();

    }

    //执行是否结束的判断
    public boolean isComplete(){
        for (Thread thread : this.workerList){
            if (thread.getState()!=Thread.State.TERMINATED){
                return false;
            }
        }
        return true;
    }

    //获得执行结果
    public ConcurrentHashMap<String,TicketStatusTask> getWorkResult(){
        return this.workResult;
    }

}
